<?php

namespace Icsoc\SecurityBundle\Controller;

use Icsoc\CoreBundle\Controller\BaseController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Icsoc\SecurityBundle\Entity\CcCcodConfigs;
use Icsoc\SecurityBundle\Entity\SwjHangupSms;
use Symfony\Component\VarDumper\VarDumper;

/**
 * 用户相关
 * Class UserController
 * @package Icsoc\SecurityBundle\Controller
 */
class UserController extends BaseController
{
    /**
     * 修改密码
     * @param Request $request
     * @return Response
     */
    public function updatePasswordAction(Request $request)
    {
        $user = $this->getUser();
        $id = $user->getId();
        $flag = $user->getFlag();
        if ($flag == 'agent') {
            $str  = 'WinAgent';
            $password = 'agPassword';
        } elseif ($flag == 'ccod') {
            $str  = 'CcCcods';
            $password = 'adminPassword';
        } else {
            //大账号不允许修改
            return new Response($this->trans('Change the password is not allowed'));
        }
        $data = $agent = $this->getDoctrine()->getRepository("IcsocSecurityBundle:".$str)->find($id);
        $form = $this->createForm('security'.$str, $data);
        if ($request->isMethod('POST')) {
            $form = $form->handleRequest($request);
            if ($form->isValid()) {
                $newPassWord = $form->get($password)->getData();
                $function = 'set'.ucfirst($password);
                $md5Password = $this->get('security.password_encoder')->encodePassword($this->getUser(), $newPassWord);
                $agent->$function($md5Password);
                $em = $this->getDoctrine()->getManager();
                $em->flush();
                $mqData = array(
                    'ag_id' => $id,
                    'vcc_id' => $user->getVccId(),
                    'ag_password' => $md5Password,
                );
                $this->get('icsoc_data.model.agent')->writeMq(array('action' => 'update', 'data' => $mqData));
                $data = array(
                    'data'=>array(
                        'msg_detail'=>$this->get('translator')->trans('Change password successfully'),
                        'type'=>'success',
                        'link' => array(
                            array(
                                'text'=> $this->get('translator')->trans('Sign out'),
                                'href'=>$this->generateUrl("icsoc_security_logout"),
                                'type'=>2,
                            ),
                        )
                    )
                );
                return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
            }
        }
        return $this->render(
            "IcsocSecurityBundle:User:updatePassword.html.twig",
            array('form'=>$form->createView(),'flag'=>$flag)
        );
    }

    /**
     * 检查旧密码
     * @param Request $request
     * @return Response
     */
    public function checkPassAction(Request $request)
    {
        $flag = $request->get("flag", '');
        $oldPass = $request->get("old_pass", '');
        $user = $this->getUser();
        $vccCode = $user->getVccCode();
        $username = $user->getAdminName();
        $password = $this->get('security.password_encoder')->encodePassword($user, $oldPass);
        $em = $this->getDoctrine()->getManager();
        $flags = "false";
        if ($flag == 'ccod' && !empty($oldPass)) {
            $arr = $em->getRepository("IcsocSecurityBundle:CcCcods")
                ->findBy(array('vccCode'=>$vccCode,'adminPassword'=>$password, 'adminName'=>$username));
            if (count($arr) >= 1) {
                $flags = "true";
            }
        } elseif ($flag == 'agent') {
            $arr = $em->getRepository("IcsocSecurityBundle:WinAgent")
                ->findBy(array('vccCode'=>$vccCode,'agPassword'=>$password,'agNum'=>$username, 'isDel'=>0));
            if (count($arr) >= 1) {
                $flags = "true";
            }
        }
        return new Response($flags);
    }

    /**
     * 恢复默认满意语音
     * @return JsonResponse|Response
     */
    public function evaluateDefaultAction()
    {
        $user = $this->getUser();
        $vccId = $user->getVccId();
        $em = $this->getDoctrine()->getManager();
        /** @var \Icsoc\SecurityBundle\Entity\CcCcods $ccod */
        $ccod = $em->getRepository("IcsocSecurityBundle:CcCcods")->find($vccId);
        if (!$ccod) {
            return new JsonResponse(array('error'=>1));
        }
        $ccod->setIsDefault(1);
        $ccod->setEvaluateSound('');
        $ccod->setSystemSound('');
        $em->flush();
        $winIp = $this->get('icsoc_core.common.class')->newGetWinIp();
        $res = $this->get('icsoc_data.validator')->reloadVcc($vccId, $winIp);
        if (!$res) {
            return new JsonResponse(array('error'=>2));
        }
        return new JsonResponse(array('error'=>0));
    }

    /**
     * 收听当前满意度语音；
     * @return Response
     */
    public function evaluatePlayAction()
    {
        $vccId = $this->getVccId();
        $em = $this->getDoctrine()->getManager();
        /** @var \Icsoc\SecurityBundle\Entity\CcCcods $ccod */
        $ccod = $em->getRepository("IcsocSecurityBundle:CcCcods")->find($vccId);
        $isDefault = $ccod->getIsDefault();
        $flysystem = $this->get("icsoc_filesystem");
        if ($isDefault == 1) {
            $address = $this->container->getParameter('sound_local_upload_path').'/evabegin.wav';
        } else {
            $address = $ccod->getEvaluateSound();
        }
        try {
            $content = $flysystem->read($address);

            return new Response($content, 200, array(
                'Pragma' => 'Public',
                'Expires' => 0,
                'Cache-Component' => 'must-revalidate, post-check=0, pre-check=0',
                'Content-type' => 'audio/x-wav',
                'Content-Length' => strlen($content),
                'Content-Transfer-Encoding' => 'binary',
                'Accept-Ranges' => 'bytes',
                'Content-Disposition' => 'attachment;filename='.basename($address),
            ));
        } catch (\Exception $e) {
            $this->get('logger')->error($e->getMessage());

            return new Response("语音不存在");
        }
    }

    /**
     * 设置信息
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function settingAction(Request $request)
    {
        $user = $this->getUser();
        $vccId = $user->getVccId();
        $isConnect = $isBusy = 0;
        $isOrigin = $this->container->get('icsoc_data.model.evaluate')->getEvaluateVerByVccId($vccId);
        $config = $this->getDoctrine()
            ->getRepository("IcsocSecurityBundle:CcCcodConfigs")
            ->findOneBy(array('vccId'=>$vccId));
        //查询技能组的情况
        $tellevel = $this->get("doctrine.dbal.default_connection")->fetchColumn(
            "SELECT tellevel FROM win_queue WHERE vcc_id = ? AND is_del = 0 LIMIT 1",
            array($vccId)
        );
        $isEnableEvaluate = 0;
        if (!empty($tellevel & 64)) {
            $config->setIsEnableEvaluate(1);
            $isEnableEvaluate = 1;
        }

        /** @var \Icsoc\SecurityBundle\Entity\SwjHangupSms $swjHangup */
        /*$swjHangup = $this->getDoctrine()->getRepository("IcsocSecurityBundle:SwjHangupSms")
            ->findOneBy(array('vccId' => $vccId));*/
        $conFlag = $smsFlag = false;
        if (empty($config)) {
            $config = new CcCcodConfigs();
            $ccods = $this->getDoctrine()->getRepository('IcsocSecurityBundle:CcCcods')->find($vccId);
            $config->setToolBarOptions($ccods);
            $conFlag = true;
        }
        /*if (empty($swjHangup)) {
            $swjHangup = new SwjHangupSms();
            $swjHangup->setVccCode($user->getVccCode());
            $swjHangup->setVccId($vccId);
            $smsFlag = true;
        } else {
            $isConnect = $swjHangup->getIsConnect();
            $isBusy = $swjHangup->getIsBusy();
        }*/
        //$config->setSmsOptions($swjHangup);
        $evaluateSound = $config->getToolBarOptions()->getEvaluateSound();
        $whiteSound = $config->getWhiteSound();
        if (!empty($evaluateSound)) {
            $winSound =  $sounds = $this->getDoctrine()->getRepository("IcsocSecurityBundle:WinSounds")
                ->findOneBy(array('address'=>$evaluateSound, 'vccId'=>$vccId));
            if (!empty($winSound)) {
                $config->getToolBarOptions()->setEvaluateSound($sounds->getId()); //用于页面展示
            }
        }
        if (!empty($whiteSound)) {
            $winSound =  $sounds = $this->getDoctrine()->getRepository("IcsocSecurityBundle:WinSounds")
                ->findOneBy(array('address'=>$whiteSound, 'vccId'=>$vccId));
            if (!empty($winSound)) {
                $config->setWhiteSound($sounds->getId()); //用于页面展示
            }
        }
        $form = $this->createForm('settingForm', $config);
        if ($request->isMethod('POST')) {
            $form->handleRequest($request);
            if ($form->isValid()) {
                $soundId = $config->getToolBarOptions()->getEvaluateSound();
                if (!empty($soundId)) {
                    $sounds = $this->getDoctrine()->getRepository("IcsocSecurityBundle:WinSounds")->find($soundId);
                    $address = $sounds->getAddress();
                    $config->getToolBarOptions()->setEvaluateSound($address);//存库;
                    $paths = explode('/', $address);
                    $count = count($paths);
                    if (!empty($paths) && $count > 3) {
                        //更改system_address;
                        $systemArres = $this->container
                                ->getParameter('sound_address').'/'.$paths[$count-2].'/'.$paths[$count-1];
                        $config->getToolBarOptions()->setSystemSound($systemArres);
                        $config->getToolBarOptions()->setIsDefault(0);//把默认改成0;
                    }
                }
                $whiteId = $config->getWhiteSound();
                if (!empty($whiteId) && $config->getIsEnableWhite() && $config->getWhiteType() == 2) {
                    $sounds = $this->getDoctrine()->getRepository("IcsocSecurityBundle:WinSounds")->find($whiteId);
                    $address = $sounds->getAddress();
                    $whiteSoundAddress = $sounds->getSoundsAddress();
                    $config->setWhiteSound($address);
                    $config->setWhiteSoundAddress($whiteSoundAddress);
                } else {
                    $config->setWhiteSound("");
                }
                $config->setConnNum(implode(',', $form->get('connNum')->getData()));
                $config->setLostNum(implode(',', $form->get('lostNum')->getData()));
                $em = $this->getDoctrine()->getManager();
                if ($conFlag) {
                    $config->setVccId($vccId);
                    $em->persist($config);
                }
                if ($isEnableEvaluate != $config->getIsEnableEvaluate()) {
                    //如果有变动；
                    $allQues = $this->get('doctrine.dbal.default_connection')->fetchAll(
                        "SELECT id,tellevel FROM win_queue WHERE vcc_id = ? AND is_del = 0",
                        array($vccId)
                    );
                    foreach ($allQues as $que) {
                        $tellevel = $config->getIsEnableEvaluate() == 1 ? ($que['tellevel'] | 0x40) : ($que['tellevel'] & ~0x40);
                        $this->get('doctrine.dbal.default_connection')
                            ->update('win_queue', array('tellevel'=>$tellevel), array('id'=>$que['id']));
                    }

                    //重载技能组
                    $winIp = $this->get('icsoc_core.common.class')->newGetWinIp();
                    $port = $this->getParameter('win_socket_port');
                    $this->get('icsoc_data.validator')->wintelsReload($vccId, $winIp, $port);
                }

                if ($smsFlag) {
                    $sms = $config->getSmsOptions();
                    $connectSms = $sms->getConnectSms();
                    $buySms = $sms->getBusySms();
                    if (empty($connectSms)) {
                        $sms->setConnectSms("");
                    }
                    if (empty($buySms)) {
                        $sms->setBusySms("");
                    }
                    $em->persist($sms);
                }
                $em->flush();
                $data = array(
                    'data'=>array(
                        'msg_detail'=>$this->get('translator')->trans('Successful configuration'),
                        'type'=>'success',
                        'link' => array(
                            array(
                                'text'=> $this->get('translator')->trans('Option to set the success'),
                                'href'=> $this->generateUrl('icsoc_security_setting')
                            ),
                        )
                    )
                );
                //重载中间件；
                $winIp = $this->get('icsoc_core.common.class')->newGetWinIp();
                $this->get('icsoc_data.validator')->reloadVcc($vccId, $winIp);
                return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
            }
        }

        return $this->render(
            'IcsocSecurityBundle:Security:setting.html.twig',
            array(
                'form'=>$form->createView(),
                'isBusy' => $isBusy,
                'isConnect' => $isConnect,
                'isOrigin' => $isOrigin
            )
        );
    }
}
